package com.example.communist_app_api.service.impl;

import cn.hutool.json.JSONException;
import com.example.communist_app_api.service.SmsService;
import com.example.communist_app_api.util.RedisUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Random;


/**
 * @author Brother Sheng Editor
 * @version 1.0
 * Create by 2023/2/18 23:28
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${tx.sms.secretId}")
    private String secretId;
    @Value("${tx.sms.secretKey}")
    private String secretKey;
    @Value("${tx.sms.sdkAppId}")
    private int sdkAppId;
    @Value("${tx.sms.templateId}")
    private Integer templateId;
    @Value("${tx.sms.appKey}")
    private String appKey;
    public static final String SIGN = "小敏文字识别小程序";
    @Resource
    RedisUtil redisUtil;

    public String sendMsg(String phone) {
        // 生成随机数
        String code = createRandom();
        SmsSingleSenderResult result = null;
        try {
            // 模板需要的参数
            String[] params = {code};
            SmsSingleSender ssender = new SmsSingleSender(sdkAppId, appKey);
            // 单发短信
            result = ssender.sendWithParam("86", phone, templateId, params, SIGN, "", "");
        } catch (JSONException e) {
            // json解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络IO错误
            e.printStackTrace();
        } catch (HTTPException e) {
            e.printStackTrace();
        }
        // 保存验证码到redis
        redisUtil.set(phone, code, 600);
        if (!"OK".equals(result.errMsg)) {
            return "验证码发送失败";
        }
        return result.errMsg;
    }

    /**
     * 验证码长度（通过更改i的最大值）
     * 获取6位随机数
     * @return
     */
    public String createRandom(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++)
        {
            result+=random.nextInt(10);
        }
        return result;
    }
}
